package com.yuyu.qingmangmall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.common.utils.R;
import com.yuyu.qingmangmall.ware.dao.WareInfoDao;
import com.yuyu.qingmangmall.ware.entity.WareInfoEntity;
import com.yuyu.qingmangmall.ware.feign.MemberFeignService;
import com.yuyu.qingmangmall.ware.service.WareInfoService;
import com.yuyu.qingmangmall.ware.vo.FareVo;
import com.yuyu.qingmangmall.ware.vo.MemberAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 仓库列表
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        // 查询条件
        String key = (String) params.get("key");

        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isNullOrEmpty(key)){
            wrapper.and(wrap->{
                wrap.eq("id",key)
                        .or().like("name",key)
                        .or().like("address",key)
                        .or().like("areacode",key);
            });

        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R info = memberFeignService.info(addrId);
        if (info!=null&&info.getCode()==0){
            MemberAddressVo receiveAddress = info.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
            });
            fareVo.setAddressVo(receiveAddress);
            String phone = receiveAddress.getPhone();
            String substring = phone.substring(phone.length() - 2, phone.length()-1);
            fareVo.setFare(new BigDecimal(substring));
        }
        return fareVo;
    }

}